package com.ybfenpan.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.log4j.Logger;

import com.ibatis.common.resources.Resources;

public class DBUtils {

	private static Logger LOG = Logger.getLogger(DBUtils.class.getName());

	/**
	 * 
	 * @param
	 * @param
	 * @param
	 * @param
	 * @param
	 * @throws Exception
	 */
	public void execSqlFileByMysql() throws Exception {

		Properties props = Resources.getResourceAsProperties("config/jdbc/jdbc.properties");
		String url = props.getProperty("jdbc.url");
		String driver = props.getProperty("jdbc.driver");
		String username = props.getProperty("jdbc.username");
		String password = props.getProperty("jdbc.password");
		File f = new File(this.getClass().getResource("").getPath()); // 获取当前类的路径

		Exception error = null;
		Connection conn = null;
		try {
			Class.forName(driver);
			conn = DriverManager.getConnection(url, username, password);
			ScriptRunner runner = new ScriptRunner(conn);
			// 下面配置不要随意更改，否则会出现各种问题
			runner.setAutoCommit(true);// 自动提交
			runner.setFullLineDelimiter(false);
			runner.setDelimiter(";");// //每条命令间的分隔符
			runner.setSendFullScript(false);
			runner.setStopOnError(false);
			// runner.setLogWriter(null);//设置是否输出日志
			// 如果又多个sql文件，可以写多个runner.runScript(xxx),
			runner.runScript(new InputStreamReader(new FileInputStream(f + "/ini_log.sql"), "utf-8"));
			runner.runScript(new InputStreamReader(new FileInputStream(f + "/ini.sql"), "utf-8"));
			runner.runScript(new InputStreamReader(new FileInputStream(f + "/ini_shop.sql"), "utf-8"));

			System.out.println("运行结束！");
			System.out.println("-------f------" + f);
			close(conn);
		} catch (Exception e) {
			LOG.error("执行sql文件进行数据库创建失败....", e);
			error = e;
		} finally {
			close(conn);
		}
		if (error != null) {
			throw error;
		}
	}

	private static void close(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			if (conn != null) {
				conn = null;
			}
		}
	}
}
